package com.xmy.first;

// 定时器的使用

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
//        定时器的常用两种方式
        timerTask();
        poolTask();
    }

    private static void timerTask() throws InterruptedException {
        Timer timer = new Timer();

        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        };

        long delay = 3 * 1000;  // 延时开始执行任务
        long period = 1 * 1000; // 执行间隔
        timer.schedule(timerTask, delay, period);

        Thread.sleep(5000);

        timer.cancel();
        timer.purge();
    }

    private static void poolTask() {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(10);

        service.scheduleAtFixedRate(() -> {
            System.out.println("world");

        }, 2000, 2000, TimeUnit.MILLISECONDS);

    }

}
